import { storage } from "@ey-utils/utils/utils";
import _ from 'lodash';
import { MetaSorted, PageConfigNew, PageType } from 'schema-form';
import components from '@/components/schema-form-render/schema-components-registed/components-biz';

const printLog = (log: string, color: string = 'green') => {
  // @ts-ignore
  if (DEV === 'development') {
    let error = storage.getItem('renderError');
    console.log(`%c ... ${log} `, `font-size:12px;color:${color};background:white;`);
    if (!error.info) {
      error.info = [];
    }
    error.info.push(log);
    storage.updateItem('renderError', error);
  }
};
/**
 * @description 获取所有类型数据
 * @param metas
 * @param pageConfig
 * @param type
 * @returns MetaSorted
 */
const getMetaSorted = (pageConfig: PageConfigNew): MetaSorted => {
  const buttons: any = [];
  const columns: any = [];
  const tableButtons: any = [];
  const searchColumns: any = [];
  const tableColumns: any = [];
  const searchButtons: any = [];
  const values: any = {};
  const detailValues: any = {};
  const valuesADetail: any = {};
  const remotes: any = [];
  const metas = pageConfig.pageDatas;
  // 排序后的分组
  pageConfig.group = _.sortBy(pageConfig.group, (o) => o.seq);
  metas?.map((o: any) => {
    switch (o.type) {
      case 'button':
        buttons.push(o);
        break;
      case 'column':
        columns.push(o);
        values[o.key] = o.value;
        detailValues[o.key] = o.detailValue;
        valuesADetail[o.key] = { value: o.value, detailValue: o.detailValue };
        break;
      case 'table_button':
        tableButtons.push(o);
        break;
      case 'search_column':
        values[o.key] = o.value;
        detailValues[o.key] = o.detailValue;
        valuesADetail[o.key] = { value: o.value, detailValue: o.detailValue };
        searchColumns.push(o);
        break;
      case 'table_column':
        tableColumns.push(o);
        break;
      case 'search_button':
        searchButtons.push(o);
        break;
    }
  });
  return {
    buttons,
    columns,
    tableButtons,
    searchColumns,
    tableColumns,
    searchButtons,
    values,
    detailValues,
    valuesADetail,
    remotes,
    pageConfig,
  };
};

const getDefaultValue = (cache: any, meta: any) => {
  const { type } = cache;
  const { defaultValue, detailValue, value, props } = meta;
  if (type === 'DETAIL') {
    return detailValue || value;
  } else {
    return value || defaultValue || props?.attributes?.defaultValue || null;
  }
};
const filterProps = (type:PageType, obj: any) => {
  const { disabled } = obj;
  if (type === 'DETAIL') {
    return {
      'editable': false,
    }
  } else {
    return {
      disabled,
    }
  }
}
// 转化 form item 的 schema
const transSchema = (config: PageConfigNew, tansData: any[], cache: any, eventMap: object): any => {
  if (!tansData || tansData.length <= 0) {
    return [];
  }
  const { type: pType } = cache;

  return tansData?.map((i) => {
    let {
      key,
      type,
      label,
      props: {
        inputValueComponentType = 'INPUT',
        required = '0',
        disabled = '0',
        hideName,
        attributes,
        editable = '1',
        validates,
      },
    } = i;

    if (!i.props?.inputValueComponentType && i.type !== 'column') {
      printLog(
        `⚠警告，${label} ${key}字段未配置组件(inputValueComponentType=${i.props?.inputValueComponentType}), 默认设置为='INPUT'`,
        'red',
      );
    }
    if (!components[i.props?.inputValueComponentType] && i.props?.inputValueComponentType) {
      printLog(
        `⚠警告，${label} ${key}字段组件(inputValueComponentType=${i.props?.inputValueComponentType}),未注册请先到schema-components-registed/components-biz注册'`,
        'red',
      );
    }
    const exProps = filterProps(pType, {
      disabled: Boolean(+disabled),
    });

    const df = getDefaultValue(cache, i);
    const filedSchema = {
      [key]: {
        type,
        title: hideName ? '' : label,
        default: df,
        required: Boolean(+required),
        ...exProps,
        'x-component': inputValueComponentType || 'INPUT',
        'x-component-props': {
          ...attributes,
          defaultValue:df,
          eventMap, // 事件处理map
          editable: (pType as PageType) === 'DETAIL' ? false : Boolean(+editable),
        },
        'x-validator': {
          ...validates,
        },
      },
    };

    return filedSchema;
  });
};

export type initialSchemaType = 'NORMAL' | 'SEARCH' | 'DETAIL';
/*
* 获取表格的Columns
*/
const getTableColumns=(res:any)=>{
  return res.tableColumns.map((item:any)=>({
    title: item.label,
    dataIndex: item.key,
    key: item.key,
  }))
}
/*
* editableColsMap
*/
const getEditableColsMap = (res:any)=>{
  const colsMap = {

  }
  res.tableColumns.forEach((i:any) => {
    const newProps =  {...i?.props?.attributes};
    delete i?.props?.attributes;
    colsMap[i.key] = {
      component: i?.props?.inputValueComponentType || "INPUT",
      props: {...i?.props, ...newProps},
    }
  });
  return colsMap;
}
/**
 *
 * @param config 模型配置信息
 * @param type 渲染类型
 * @param eventMap 外部传入eventMap处理数据
 * @returns
 */
export const initialSchema = (
  config: PageConfigNew,
  type: initialSchemaType,
  eventMap: object = {},
): MetaSorted => {
  console.log('eventMap', eventMap)
  printLog(`啊油瑞滴!? 开始初始化数据，${config?.code}，冲冲冲~~~~`, 'blue');
  printLog(`初始化协议,类型 = ${type}`);
  const res = getMetaSorted(config);
  const columns = getTableColumns(res);
  const colsMap = getEditableColsMap(res);
  if (type === 'SEARCH') {
    res.searchButtons?.push({
      key: 'chongzhi',
      label: '重置',
      type: 'search_button',
      props: {
        hook: 'reset',
      },
    });
  }
  // TODO: 属性转换
  printLog(`元素属性转换SCHEMA开始`);
  const itemSchemas = transSchema(
    config,
    type === 'SEARCH' ? res?.searchColumns || [] : res?.columns || [],
    {
      type,
    },
    eventMap,
  );
  console.log('itemSchemas', itemSchemas);
  printLog(`元素属性转换SCHEMA结束`);
  printLog(`结束over,老铁`, 'blue');
  return {
    ...res,
    schema: itemSchemas,
    columns,
    colsMap
  };
};




const test = function() {
  console.log('fuck xxx')
}